package org.seal.security.cros_csrf_shop;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;

import javax.servlet.http.HttpServletRequest;

/**
 * 安全配置
 * @author seal
 */
@Configuration
public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {

    /**
     * 安全配置
     * 关闭 csrf 配置 cors
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 登陆方式
                .formLogin().and().httpBasic().and().
                // cors 配置
                cors().configurationSource((request) -> (buildConfig(request))).and().csrf().disable().
                // 访问控制
                authorizeRequests().antMatchers(HttpMethod.GET, "/shop/", "/").permitAll().anyRequest().authenticated();
    }

    /**
     * Cors 配置
     * @return
     */
    private CorsConfiguration buildConfig(HttpServletRequest request) {
        System.out.println(request.getMethod());
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 配置告知浏览器是否提交认证信息，例如 cookie 等信息
        corsConfiguration.setAllowCredentials(false);
        //corsConfiguration.setAllowCredentials(true);

        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    /**
     * 配置默认登陆用户名及密码 u/p 用户
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("u").password("p").roles("USER");
    }

    /**
     * 密码加密规则，spring boot 2.0 没有默认配置
     * 这里使用的是已经过期的明文比对，建议生产不要使用
     * @return
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}
